import React, {
  useState,
  FunctionComponent,
  lazy,
  Suspense,
  useEffect,
  useRef,
} from 'react';
import styles from './index.less';
import { IRouteComponentProps, useSelector, useDispatch } from 'umi';
import { Icon, Tag, Tabs, Swiper } from 'react-vant';
import { HttpService } from '@/core';
import api from '@/api';
import { IGlobalState } from '@/models/global';
import Overlay from './components/overlay';
import StoreInfo from './components/storeinfo';

type SwiperInstance = {
  swipeTo: (index: number) => void;
};

// 商品
const Sell = lazy(() => import('./components/sell'));
// 评论
const Recommend = lazy(() => import('./components/recommend'));
// 店铺
const Shop = lazy(() => import('./components/shop'));

export interface ITabsProps {
  title: string;
  active: boolean;
  name: string;
}

/** 店家信息 */
export interface IStoreProps {
  /** 店家描述 */
  description: string;
  /** 图片 */
  avatar: string;
  /** 轮播 */
  pics: Array<string>;
  /** 介绍 */
  bulletin: string;
  /** 配送费 */
  deliveryPrice: number;
  /** 平均配送时间 */
  deliveryTime: number;
  /** 评分 */
  foodScore: number;
  /** 优惠信息 */
  supports: Array<{ type: number, description: string }>;
  /** 名字 */
  name: string;
  /** 高于周边商家 */
  rankRate: number;
  /** 综合评分 */
  score: number;
  /** 总售出 */
  sellCount: number;
  /** 服务评分 */
  serviceScore: number;
  /** 评论数 */
  ratingCount: number;
  /** 最低消费 */
  minPrice: number;
}

const Order: FunctionComponent<IRouteComponentProps> = () => {

  const { basePostFree, minPrice } = useSelector((state: { globalState: IGlobalState }) => state.globalState);
  const dispatch = useDispatch();


  // shadow块dom
  const shadowDom = useRef<HTMLDivElement>(null);
  const [shadowDomDisplay, setShadowDomDisplay] = useState<boolean>(false);

  // 是否展示顶部蒙层
  const [visiblity, setVisiblity] = useState<boolean>(false);

  // 店家信息
  const [storeInfo, setStoreInfo] = useState<IStoreProps | null>(null);

  // swiper实例
  const swiperInstance: any = useRef<SwiperInstance>(null);

  // tabs数据
  const [tabs, setTabs] = useState<Array<ITabsProps>>([
    { title: '商品', name: 'sell', active: true },
    { title: '评论', name: 'recommend', active: false },
    { title: '商家', name: 'shop', active: false },
  ]);
  // tab active
  const [tabActiveName, setTabActiveName] = useState<string>('sell');

  // 切换tabs
  const onTabsChange = (e: string | number) => {
    const index = tabs.findIndex((item) => item.name === e);
    if (index !== -1 && !tabs[index].active) {
      setTabs(
        tabs.map((item, num) => ({
          ...item,
          active: index === num ? true : item.active,
        })),
      );
    }
    if (index !== -1) {
      swiperInstance.current?.swipeTo(index);
    }
  };

  // 切换swiper
  const onSwiperChange = (e: number) => {
    setTabActiveName(tabs[e].name);
    setTabs(
      tabs.map((item, num) => ({
        ...item,
        active: e === num ? true : item.active,
      })),
    );
  };

  /** 控制顶部shadow展示/隐藏 */
  const shadowDisplayChange = (show = true) => {
    setShadowDomDisplay(!show);
    if (shadowDom.current) {
      if (!show) {
        shadowDom.current.style.background = 'rgba(0,0,0,0)';
        setTimeout(() => {
          shadowDom.current && (shadowDom.current.style.zIndex = '0');
        }, 300);
      } else {
        shadowDom.current.style.zIndex = '1500';
        shadowDom.current.style.background = 'rgba(0,0,0,0.7)';
      }
    }
  };


  /** 获取店家信息 */
  const getStoreInfo = () => {
    HttpService.get(api.storeInfo, {}).then(res => {
      const { data, errno } = res as { errno: number; data: IStoreProps };
      if (data && errno === 0) {
        dispatch({ type: 'globalState/setMinPrice', payload: data.minPrice });
        dispatch({ type: 'globalState/setBasePostFree', payload: data.deliveryPrice });
        setStoreInfo(data)
      }
    })
  }


  useEffect(() => {
    getStoreInfo()
  }, [])

  return (
    <div className={styles.order_wrapper}>
      {storeInfo &&
        <Overlay visiblity={visiblity} setVisType={(type: boolean) => setVisiblity(type)}>
           <StoreInfo {...storeInfo}></StoreInfo>
        </Overlay>}
      <div ref={shadowDom} className={styles.order_wrapper_shadow}></div>
      <div onClick={() => setVisiblity(true)} className={styles.order_wrapper_header}>
        <div className={styles.order_wrapper_header_imgback}>
          <img
            src={storeInfo ? storeInfo.avatar : ''}
            alt=""
          />
        </div>
        <div className={styles.order_wrapper_header_shop}>
          <img
            src={storeInfo ? storeInfo.avatar : ''}
            alt=""
          />
          <div className={styles.order_wrapper_header_shop_content}>
            <div className={styles.order_wrapper_header_shop_content_name}>
              <Tag type="danger">品牌</Tag>
              <span className={styles.name}>{storeInfo?.name || '店铺名称'}</span>
            </div>
            <div className={styles.order_wrapper_header_shop_content_name}>
              蜂鸟专送/{storeInfo?.deliveryTime || ''}分钟送达
            </div>
            <div
              className={`${styles.order_wrapper_header_shop_content_name} ${styles.order_wrapper_header_shop_content_name_last}`}
            >
              <Tag color="#ffffff" textColor="#ff0000">
                减
              </Tag>
              {storeInfo?.supports ? storeInfo.supports[0].description : ''}
            </div>
          </div>
        </div>
        <div className={styles.order_wrapper_header_info}>
          <Tag color="#ffffff" textColor="#000000">
            公告
          </Tag>
          <span className={styles.order_wrapper_header_info_text}>{storeInfo?.bulletin}</span>
          <Icon name="arrow" />
        </div>
        <div className={styles.order_wrapper_header_shadow}></div>
      </div>
      <Tabs active={tabActiveName} onChange={onTabsChange}>
        {tabs?.map((item: ITabsProps, index: number) => (
          <Tabs.TabPane
            key={`${item.name}${index}`}
            title={item.title}
            name={item.name}
          ></Tabs.TabPane>
        ))}
      </Tabs>
      <div className={styles.order_wrapper_body_content}>
        <Swiper
          touchable={shadowDomDisplay}
          ref={swiperInstance}
          className={styles.order_wrapper_body_content_swiper}
          loop={false}
          indicator={false}
          onChange={onSwiperChange}
        >
          {tabs?.map((item: ITabsProps, index: number) => {
            let Component = null;
            switch (item.name) {
              case 'sell':
                Component = Sell;
                break;
              case 'recommend':
                Component = Recommend;
                break;
              default:
                Component = Shop;
            }
            return (
              <Swiper.Item key={'component' + index}>
                <Suspense fallback>
                  {item.active && (
                    <Component
                      shadowDisplayChange={shadowDisplayChange}
                      {...storeInfo}
                    ></Component>
                  )}
                </Suspense>
              </Swiper.Item>
            );
          })}
        </Swiper>
      </div>
    </div>
  );
};

export default Order;
